package redis.inaction.clients.configuration;

import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.cluster.RedisClusterClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


//展示 Lettuce 的几种方式
@Configuration
@ConditionalOnProperty(name = "lettuce.demonstration", havingValue = "true")
public class LettuceUsageConfiguration {

    @ConditionalOnProperty(name = "lettuce.demonstration.standalone", havingValue = "true")
    public static class StandaloneDemonstration{
        @Bean(destroyMethod = "shutdown")
        public RedisClient redisClient(@Value("${redis.host:localhost}") String host,
                                       @Value("${redis.port:6379}") int port){
            return RedisClient.create(RedisURI.create(host, port));
        }
    }

    @ConditionalOnProperty(name = "lettuce.demonstration.cluster", havingValue = "true")
    public static class ClusterDemonstration{

        @Bean
        public RedisClusterClient redisClusterClient(@Value("${redis.cluster.nodes}") String clusterNodesStr){
            List<RedisURI> clusterNodes = createClusterNodes(clusterNodesStr);
            return RedisClusterClient.create(clusterNodes);
        }

        private List<RedisURI> createClusterNodes(String clusterNodeStr){
            return Arrays.stream(clusterNodeStr.split(","))
                    .map( hostAndPortStr -> {
                        String[] hostAndPort = hostAndPortStr.trim().split(":");
                        return RedisURI.create(hostAndPort[0], new Integer(hostAndPort[1]));
                    }).collect(Collectors.toList());
        }
    }

    @ConditionalOnProperty(name = "lettuce.demonstration.sentinel", havingValue = "true")
    public static class SentinelDemonstration{
        @Bean(destroyMethod = "shutdown")
        public RedisClient redisClient(@Value("${redis.sentinel_host}") String sentinelHost,
                                       @Value("${redis.master}") String master){
            RedisURI redisUri = RedisURI.Builder.sentinel(sentinelHost, master).build();
            return RedisClient.create(redisUri);
        }

    }
}
